/******************************************************************************
 *   ObjectFS - Embedded Object File-System
 *
 *   Provides a full, simple no-nonsense file-system for simple embedded devices.
 *   Written by James Walmsley, james@fullfat-fs.co.uk
 *
 *   Copyright 2010 James Walmsley
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 *
 *   Removing the above notice is illegal and will invalidate this license.
 *****************************************************************************/


/*
	File Manager
*/

#ifdef __PIC24FJ64GB106__

#include "ofs.h"
#include "ofs_memory.h"
#include "ofs_error.h"
#include "ofs_types.h"
#include <p24fxxxx.h>
#include <string.h>

OFS_ERROR OFS_Open(OFS_MANAGER *pOMan, OFS_OBJECT *pObject, const OFS_INT8 *szpName) {
	OFS_UINT8	Dirent[32];
	OFS_INT		i;

	for(i = 0; i < pOMan->ulTotalDescriptors; i++) {
		OFS_ReadDevice(pOMan, (i*32) + 32, 32, Dirent);

		if(OFS_getLong(Dirent, 0x00) != 0xFFFFFFFF && OFS_getLong(Dirent, 0x00) != 0x00000000) {
			if(!strncmp(szpName, (OFS_INT8*) &Dirent[16], 16)) {
				pObject->FilePointer = 0;
				pObject->pOMan = pOMan;
				pObject->eType = OFS_getLong(Dirent, 0x00);
				pObject->ulSize = OFS_getLong(Dirent, 0x08);
				pObject->ulStartAddress = OFS_getLong(Dirent, 0x04);
				pObject->oTypeData.u32 = OFS_getLong(Dirent, 0x0C);
				return OFS_ERR_NONE;
			}
		}
	}

	return OFS_ERR_NOT_FOUND;
}

OFS_UINT32 OFS_Read(OFS_OBJECT *pObject, OFS_UINT32 nSize, void *pBuffer, OFS_ERROR *pError) {
	OFS_UINT unReadSize = nSize;

	if((nSize + pObject->FilePointer) > pObject->ulSize) {
		nSize = pObject->ulSize - pObject->FilePointer;
	}

	OFS_ReadDevice(pObject->pOMan, pObject->ulStartAddress + pObject->FilePointer, unReadSize, pBuffer);

	if(pError) {
		*pError = OFS_ERR_NONE;
	}

	pObject->FilePointer += nSize;

	return unReadSize;
}


OFS_UINT32 OFS_Write(OFS_OBJECT *pObject, OFS_UINT32 nSize, void *pBuffer, OFS_ERROR *pError) {
	OFS_UINT32 unWriteSize = nSize;

	if(nSize > 256) {
		Nop();
	}

	if((nSize + pObject->FilePointer) > pObject->ulSize) {
		nSize = pObject->ulSize - pObject->FilePointer;
	}

	OFS_WriteDevice(pObject->pOMan, (unsigned long)((unsigned long)(pObject->ulStartAddress) + (unsigned long)(pObject->FilePointer)), unWriteSize, pBuffer);

	pObject->FilePointer += nSize;

	return unWriteSize;
}

#endif